package netty.study.third.chat.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.UUID;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName MyServerHandler.java
 * @Description TODO
 * @createTime 2020年04月13日 14:23:00
 * <p>
 * <p>
 * SimpleChannelInboundHandler中的泛型是请求的对象
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

	//一个单利的对象。在任务队列里面1秒钟之内没新任务的时候会自动停止，不适用于大量的任务
	private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		Channel channel = ctx.channel();
		channelGroup.forEach(ch -> {
			if (ch != channel) {
				ch.writeAndFlush(channel.remoteAddress()+"发送的消息："+msg);
			}else {
				ch.writeAndFlush("【自己】"+msg);
			}
		});
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		channelGroup.writeAndFlush("【服务器】-" + channel.remoteAddress() + "加入\n");
		channelGroup.add(channel);
	}

	//会自动的将channelGroup中断开的channel移除掉
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		channelGroup.writeAndFlush("【服务器】-" + channel.remoteAddress() + "离开\n");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		System.out.println(channel.remoteAddress() + "上线");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		System.out.println(channel + "下线");
	}

	/**
	 * 处理出现异常的时候，进行处理的逻辑
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
